package com.kangjia.model.m1.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.kangjia.general.dao.GeneralDao;
import com.kangjia.model.m1.entity.Org;
import com.kangjia.model.service.TreeService;

import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

@Service
public class OrgService extends TreeService<Org> {

	@Autowired
	protected JedisPool jedisPool;
	@Autowired
	private GeneralDao generalDao;
	
	public void createOrgCode(Org org) {
		String fp = null;
		String preffix = "org";
		if (org.getOrgId() == null) {
			if (org.getParentId() != null) {
				Org entity = generalDao.get(Org.class, org.getParentId());
				if (entity != null) {
					preffix += "," + entity.getCode();
					fp = entity.getCode();
				}				
			}
			Jedis jedis = jedisPool.getResource();
			try {
				Long l = jedis.hincrBy("key.org.code", preffix, 1);
				String s = String.format("%03d", l);
				fp = (fp != null ? fp + s : s);
			} finally {
				if (jedis != null) {
					jedis.close();
				}
			}
			org.setCode(fp);
		}
	}
	
	public Org createT() {
		return new Org();
	}

	public Integer getId(Org entity) {
		return entity.getOrgId();
	}

	public Integer getParent(Org entity) {
		return entity.getParentId();
	}

	public void addChildren(Org entity, Org node) {
		entity.getChildren().add(node);
	}

	public void checked(Org entity, boolean is) {
		entity.setChecked(is);
	}

	public void expand(Org entity, boolean is) {
		entity.setExpanded(is);
	}

}
